#!/usr/bin/env node

import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
  CallToolRequestSchema,
  ListToolsRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';

import { TOOL_DEFINITIONS } from './tools/ToolDefinitions.js';
import { ToolHandlers } from './handlers/ToolHandlers.js';
import { CallToolHandler } from './handlers/CallToolHandler.js';

class Java8SpringBootRefactorServer {
  private server: Server;
  private toolHandlers: ToolHandlers;
  private callToolHandler: CallToolHandler;

  constructor() {
    this.server = new Server(
      {
        name: 'java8-springboot-refactor',
        version: '1.0.0'
      },
      {
        capabilities: {
          tools: {}
        }
      }
    );

    this.toolHandlers = new ToolHandlers();
    this.callToolHandler = new CallToolHandler(this.toolHandlers);
    this.setupHandlers();
  }

  private setupHandlers() {
    this.server.setRequestHandler(ListToolsRequestSchema, async () => {
      return {
        tools: TOOL_DEFINITIONS
      };
    });

    this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
      const { name, arguments: args } = request.params;

      try {
        const result = await this.callToolHandler.handleToolCall(name, args);

        return {
          content: [
            {
              type: 'text',
              text: typeof result === 'string' ? result : JSON.stringify(result, null, 2)
            }
          ]
        };
      } catch (error) {
        return {
          content: [
            {
              type: 'text',
              text: `执行工具 ${name} 时发生错误: ${error instanceof Error ? error.message : String(error)}`
            }
          ]
        };
      }
    });
  }

  async run() {
    const transport = new StdioServerTransport();
    await this.server.connect(transport);
    console.error('Java8-SpringBoot重构MCP服务器已启动');
  }
}

const server = new Java8SpringBootRefactorServer();
server.run().catch(console.error);